import 'package:get/get.dart';
import 'package:mziot/app/config/constant.dart';
import 'package:mziot/app/routes/app_pages.dart';
import 'package:mziot/app/tools/blue_service.dart';
import 'package:mziot/app/tools/global_const.dart';
import 'package:mziot/app/tools/tools.dart';
import 'package:mziot/generated/json/base/json_convert_content.dart';

class BaseModel<T> {
  int? status;
  String? statusMsg;

  int? code;
  String? msg;
  String? subcode;
  String? submsg;
  dynamic oriResponse;
  T? data;
  bool isSuccess = false;

  BaseModel({this.code, this.msg, this.subcode, this.submsg, this.data});

  BaseModel.fromJson(response) {
    status = response?.statusCode;
    statusMsg = response?.statusMessage;

    if (status != 200 || response?.data == null) {
      return;
    }
    try {
      Map<String, dynamic> object = response!.data;
      oriResponse = object;
      if (object['code'] is String) {
        code = int.parse(object['code'] ?? '-1');
      } else {
        code = object['code'];
      }
      if (code == 0) {
        isSuccess = true;
      } else if (code == 102) {
        BlueService.share.stopScan();
        BlueService.share.disConnectDevice();
        GlobalConst.tempModel = null;
        GlobalConst.sharedPreferences?.remove(Constant.kUser);
        Get.offAllNamed(Routes.AUTH_LOGIN);
        return;
      }
      msg = object['msg'];
      subcode = object['subcode'];
      submsg = object['submsg'];
      final objectData = object['data'];
      if (objectData != null && objectData != 'null') {
        if ((objectData is Map || objectData is List) && !(T.toString().contains('dynamic'))) {
          data = JsonConvert.fromJsonAsT<T>(objectData);
        } else {
          data = object['data'];
        }
      }
    } catch (e) {
      code = -888;
      msg = '数据解析异常';
      logger.v(e.toString());
    }
  }

  Map<String, dynamic> toJson() {
    final data = <String, dynamic>{};
    data['code'] = code;
    data['msg'] = msg;
    data['subcode'] = subcode;
    data['submsg'] = submsg;
    data['data'] = this.data;
    return data;
  }
}
